package indiwood.model.service;

import indiwood.model.AwardVO;
import indiwood.model.CinemaListVO;
import indiwood.model.CinemaVO;
import indiwood.model.DirectorListVO;
import indiwood.model.DirectorVO;
import indiwood.model.MemberListVO;
import indiwood.model.MemberVO;
import indiwood.model.MovieListVO;
import indiwood.model.MovieVO;
import indiwood.model.PagingBean;
import indiwood.model.ScheduleDateVO;
import indiwood.model.ScheduleTimeVO;
import indiwood.model.ShowingListVO;
import indiwood.model.ShowingVO;
import indiwood.model.dao.AdminDAO;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class AdminServiceImpl implements AdminService {
	@Resource(name = "adminDAOImpl")
	private AdminDAO adminDAO;
	@Resource(name="uploadPath")
	private String path;
	// 파일 업로드
	public String fileUpload(MultipartFile uploadFile, String folder){
		String fileName = uploadFile.getOriginalFilename();
		File copyFile = null;
		if(uploadFile!=null&&!uploadFile.isEmpty()){ // 파일이 존재
			copyFile = new File(path+folder+System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf(".")));
			try {
				uploadFile.transferTo(copyFile);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		}
		return copyFile.getName();
	}
	// 업로드된 파일 삭제
	public void fileDelete(String filePath){
		String fp[] = filePath.split("/");
		String fpath = path;
		for(int i=1;i<fp.length;i++){
			fpath+=fp[i];
			if(i<fp.length-1)
				fpath+="\\";
		}
		File file = new File(fpath);
		if(file.exists())
			file.delete();
	}
	@Override
	public DirectorListVO directorList(String pageNo) {
		if(pageNo==null||pageNo=="") 
			pageNo="1";
		List<DirectorVO> dlist=adminDAO.getDirectorList(pageNo);
		int total=adminDAO.directorTotalContent();
		PagingBean paging=new PagingBean(total,Integer.parseInt(pageNo));
		DirectorListVO dlvo=new DirectorListVO(dlist, paging);
		return dlvo;
	}
	@Override
	public HashMap<String, Object> directorContent(int no) {
		HashMap<String, Object> directorDetailMap = new HashMap<String, Object>();
		DirectorVO dvo = adminDAO.getDirectorContent(no);
		directorDetailMap.put("directorContent", dvo);
		List<MovieVO> mlist = adminDAO.getMovieListByDirectorNo(dvo.getDirectorNo());
		directorDetailMap.put("movielist", mlist);
		String awardstr = "";
		for(int i=0; i<mlist.size();i++){ // 영화 리스트를 반복문을 돌려 하나씩 확인
			List<String> alist = adminDAO.getAwardList(mlist.get(i).getMovieNo()); // 영화번호에 해당되는 수상리스트를 검색
			for(int j=0;j<alist.size();j++){ // 수상리스트를 반복문을 돌려 하나씩 확인
				if(awardstr.indexOf(alist.get(j))==-1){ // awardstr 에 해당 수상정보가 없으면
					awardstr += alist.get(j); // awardstr 에 수상정보 추가
					if(j<alist.size()-1){
						awardstr += ", ";
					}
				}
			}
		}
		directorDetailMap.put("awardlist", awardstr);
		return directorDetailMap;
	}
	@Override
	public void directorWrite(DirectorVO dvo, MultipartFile uploadFile) {
		String fileName = fileUpload(uploadFile, "director\\");
		dvo.setDirectorImgPath("upload/director/"+fileName);
		adminDAO.directorWrite(dvo);
	}
	@Override
	public void directorDelete(int no) {
		DirectorVO dvo = adminDAO.getDirectorContent(no);
		fileDelete(dvo.getDirectorImgPath());
		// 감독정보에 해당하는 영화정보 가져와서
		List<MovieVO> mlist = adminDAO.getMovieListByDirectorNo(no);
		for(int i=0; i<mlist.size();i++){ // 영화 리스트를 반복문을 돌려 하나씩 확인
			adminDAO.deleteAward(mlist.get(i).getMovieNo()); // award 부터 삭제
			MovieVO mvo = adminDAO.movieContent(mlist.get(i).getMovieNo()); // 영화번호에 해당하는 정보가져와서
			fileDelete(mvo.getPosterPath()); // 해당 포스터 삭제
		}
		adminDAO.deleteMovieByDirectorNo(no); // movie 삭제
		adminDAO.deleteDirector(no); // director 삭제
	}
	@Override
	public DirectorVO directorUpdateView(int no) {
		return adminDAO.getDirectorContent(no);
	}
	@Override
	public void movieWrite(MovieVO mvo, AwardVO avo, MultipartFile posterFile) {
		String posterFileName = fileUpload(posterFile, "movie\\poster\\");
		mvo.setPosterPath("upload/movie/poster/"+posterFileName);
		adminDAO.movieWrite(mvo);
		if(!(avo.getInfo().equals("")||avo.getInfo().equals(null))){
			avo.setMovieNo(mvo.getMovieNo());
			String awardInfo[] = avo.getInfo().split(",");
			for(int i=0;i<awardInfo.length;i++){
				AwardVO vo = avo;
				vo.setInfo(awardInfo[i]);
				adminDAO.writeAward(vo);
			}
		}
	}
	@Override
	public HashMap<String, Object> movieContent(int no) {
		HashMap<String, Object> mcMap = new HashMap<String, Object>();
		mcMap.put("movieContent", adminDAO.movieContent(no));
		String awardContent = "";
		List<String> alist = adminDAO.getAwardList(no); // 영화번호에 해당되는 수상리스트를 검색
		for(int j=0;j<alist.size();j++){ // 수상리스트를 반복문을 돌려 하나씩 확인
			if(awardContent.indexOf(alist.get(j))==-1){ // awardstr 에 해당 수상정보가 없으면
				awardContent += alist.get(j); // awardstr 에 수상정보 추가
				if(j<alist.size()-1){
					awardContent += ", ";
				}
			}
		}
		mcMap.put("awardContent", awardContent);// 수상 정보 추가
		List<ShowingVO> slist = adminDAO.getShowingList(no); // 영화번호에 해당되는 상영 리스트 검색
		mcMap.put("showingList", slist);
		mcMap.put("cinemaList", adminDAO.getAllCinemaList());
		return mcMap;
	}
	@Override
	public MovieListVO movieList(String pageNo) {
		if(pageNo==null||pageNo=="")
			pageNo="1";
		List<MovieVO> mlist=adminDAO.movieList(pageNo);
		int total=adminDAO.movieTotalContent();
		PagingBean paging=new PagingBean(total,Integer.parseInt(pageNo));
		MovieListVO lvo=new MovieListVO(mlist, paging);
		return lvo;
	}
	@Override
	public void directorUpdate(DirectorVO dvo, MultipartFile uploadFile) {
		if(uploadFile!=null&&!uploadFile.isEmpty()){ // 파일이 존재
			fileDelete(dvo.getDirectorImgPath());
			String fileName = fileUpload(uploadFile, "director\\");
			dvo.setDirectorImgPath("upload/director/"+fileName);
		}
		adminDAO.directorUpdate(dvo);
	}
	@Override
	public CinemaListVO cinemaList(String pageNo) {
		if(pageNo==null||pageNo=="") 
			pageNo="1";
		List<CinemaVO> clist=adminDAO.getCinemaList(pageNo);
		int total=adminDAO.cinemaTotalContent();
		PagingBean paging=new PagingBean(total,Integer.parseInt(pageNo));
		CinemaListVO clvo=new CinemaListVO(clist, paging);
		return clvo;
	}
	@Override
	public CinemaVO cinemaContent(int no) {
		return adminDAO.cinemaContent(no);
	}
	@Override
	public void cinemaDelete(int no) {
		adminDAO.cinemaDelete(no);
	}
	@Override
	public CinemaVO cinemaUpdateView(int no) {
		return adminDAO.cinemaContent(no);
	}
	@Override
	public void cinemaUpdate(CinemaVO cvo) {
		adminDAO.cinemaUpdate(cvo);
	}
	@Override
	public void cinemaWrite(CinemaVO cvo) {
		adminDAO.cinemaWrite(cvo);
	}
	@Override
	public HashMap<String, Object> movieUpdateView(int no) {
		HashMap<String, Object> updateMap = new HashMap<String, Object>();
		MovieVO mvo = adminDAO.movieContent(no);
		List<DirectorVO> directorList = adminDAO.findAllDirector();
		updateMap.put("movieVO", mvo);
		updateMap.put("directorList", directorList);
		return updateMap;
	}
	@Override
	public void updateMovie(MovieVO mvo, MultipartFile posterFile) {
		if(posterFile!=null&&!posterFile.isEmpty()){ // 파일이 존재
			fileDelete(mvo.getPosterPath());
			String fileName = fileUpload(posterFile, "movie\\poster\\");
			mvo.setPosterPath("upload/movie/poster/"+fileName);
		}
		adminDAO.updateMovie(mvo);
	}
	@Override
	public void deleteMovie(int no) {
		MovieVO mvo = adminDAO.movieContent(no);
		fileDelete(mvo.getPosterPath());
		adminDAO.deleteShowing(no);
		adminDAO.deleteAward(no);
		adminDAO.deleteMovie(no);
	}
	@Override
	public void showingWrite(ShowingVO svo) {
		adminDAO.showingWrite(svo);
	}
	@Override
	public MemberListVO memberList(String pageNo) {
		if(pageNo==null||pageNo=="")
			pageNo="1";
		List<MemberVO> mlist=adminDAO.getMemberList(pageNo);
		int total=adminDAO.getTotalMemberCount();
		PagingBean paging=new PagingBean(total,Integer.parseInt(pageNo));
		MemberListVO mlvo=new MemberListVO(mlist, paging);
		return mlvo;
	}
	@Override
	public List<DirectorVO> findAllDirector() {
		return adminDAO.findAllDirector();
	}
	@Override
	public boolean checkCinema(int cinemaNo, int movieNo) {
		List<ShowingVO> slist = adminDAO.getShowingList(movieNo);
		boolean result = false;
		for(int i=0;i<slist.size();i++){
			if(slist.get(i).getCinemaVO().getCinemaNo()==cinemaNo)
				result = true;
		}
		return result;
	}
	@Override
	public void deleteShowing(int showingNo) {
		adminDAO.deleteShowingByShowingNo(showingNo);
	}
	@Override
	public HashMap<String,Object> findAllMovieInfo() {
		HashMap<String, Object> allInfoMap = new HashMap<String, Object>();
		allInfoMap.put("cinemaList", adminDAO.getAllCinemaList());		
		List<MovieVO> result = adminDAO.getExceptedMovieList();
		if(result.isEmpty()){
			allInfoMap.put("movieList", adminDAO.getAllMovieList());			
		}else{			
			allInfoMap.put("movieList", adminDAO.getExceptedMovieList());
		}		
		return allInfoMap;
	}
	@Override
	public HashMap<String,Object> getShowingListByShowingNo(int showingNo) {
		HashMap<String, Object> allInfoMap = new HashMap<String, Object>();
		allInfoMap.put("movieContent", adminDAO.movieContent(showingNo));
		allInfoMap.put("showingList", adminDAO.getShowingList(showingNo));
		allInfoMap.put("showingContent", adminDAO.getShowingContent(showingNo));
		allInfoMap.put("cinemaList", adminDAO.getAllCinemaList());
		return allInfoMap;
	}
	@Override
	public ShowingListVO getShowingListByShowingNo(String pageNo) {
		if(pageNo==null||pageNo=="")
			pageNo="1";
		List<ShowingVO> slist=adminDAO.getShowingListByPage(pageNo);
		int total=adminDAO.showingListTotalContent();
		PagingBean paging=new PagingBean(total,Integer.parseInt(pageNo));
		ShowingListVO svo=new ShowingListVO(slist, paging);
		return svo;
	}
	public HashMap<String,Object> getShowingContent(int showingNo){
		HashMap<String, Object> allInfoMap = new HashMap<String, Object>();		
		//allInfoMap.put("date", adminDAO.getScheduleDate(showingNo));
		allInfoMap.put("showingContent", adminDAO.getShowingContent(showingNo));
		return allInfoMap;
	}
	@Override
	public void updateSchedule(ScheduleDateVO sdvo) {
		ScheduleTimeVO stvo = new ScheduleTimeVO();
		TreeSet<String> treeSet= new TreeSet<String>();
		String sa[] = sdvo.getDate().split(",");
		for(int i=0;i<sa.length;i++){
			treeSet.add(sa[i].substring(0, sa[i].indexOf("|")));
		}
		Iterator<String> it = treeSet.iterator();
		while(it.hasNext()){
			sdvo.setDate(it.next());
			int confirmDate = adminDAO.confirmScheduleDateByShowingNo(sdvo);
			if(confirmDate==0){			
				adminDAO.createScheduleDate(sdvo);
			}
		}
		for(int i=0;i<sa.length;i++){
			sdvo.setDate(sa[i].substring(0, sa[i].indexOf("|")));
			int dateNo = adminDAO.getDateNo(sdvo);
			sdvo.setDateNo(dateNo);
			stvo.setScheduleDateVO(sdvo);
			stvo.setTime(Integer.parseInt(sa[i].substring(sa[i].indexOf("|")+1)));
			adminDAO.createScheduleTime(stvo);			
		}
	}
	@Override
	public List<String> getScheduleByShowingNo(int showingNo) {
		List<ScheduleTimeVO> list = adminDAO.getScheduleByShowingNo(showingNo);
		List<String> scheduleList = new ArrayList<String>();
		for(int i=0;i<list.size();i++){
			scheduleList.add(Integer.parseInt(list.get(i).getScheduleDateVO().getDate().substring(8,10))+"|"+list.get(i).getTime());
		}
		return scheduleList;
	}
	@Override
	public HashMap<String, Object> getSchedule(int showingNo) {
		HashMap<String, Object> allInfoMap = new HashMap<String, Object>();
		int lastDay=0;		
		ShowingVO svo = adminDAO.getShowingContent(showingNo);
		String year = svo.getStartDate().substring(0, 4);
		String startMonth = svo.getStartDate().substring(5, 7);
		String endMonth = svo.getEndDate().substring(5, 7);
		for ( int month = 1; month <= 12; month++ ) {
			GregorianCalendar cld = new GregorianCalendar ( 2001, month - 1, 1 );
			lastDay=cld.getActualMaximum ( Calendar.DAY_OF_MONTH );
		}
		allInfoMap.put("year", year);
		allInfoMap.put("startMonth", startMonth);
		allInfoMap.put("endMonth", endMonth);
		allInfoMap.put("date", lastDay);
		allInfoMap.put("showingContent", adminDAO.getShowingContent(showingNo));
		allInfoMap.put("scheduleList", this.getScheduleByShowingNo(showingNo));
		return allInfoMap;
	}
	@Override
	public void deleteSchedule(ShowingVO svo) {
		/*String schedule = adminDAO.getScheduleDateByShowingNo(svo.getShowingNo());
		List<String> scheduleList = new ArrayList<String>();
		StringTokenizer stk = new StringTokenizer(schedule,",");
		String finalSchedule="";
		int count = stk.countTokens();
		int whileCount = 0;
		while(stk.hasMoreTokens()){
			String nextToken = stk.nextToken();
			if(!nextToken.equals(svo.getSchedule())){
				if(whileCount==(count-1)){
					finalSchedule += nextToken;
				}else{
					finalSchedule += (nextToken+",");
				}
			}
			whileCount++;
		}
		System.out.println(finalSchedule);
		svo.setSchedule(finalSchedule);
		adminDAO.updateSchedule(svo);*/
	}
	@Override
	public int confirmShowingContent(int movieNo) {
		return adminDAO.confirmShowingContent(movieNo);
	}
}
